<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { DeleteOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import type { TableColumnsType } from 'ant-design-vue';
import { getMqMessageRecords } from '@/service/api/mq-message';

// 历史记录相关状态
const showHistoryDetail = ref(false);
const selectedHistoryRecord = ref<any>(null);
const historyData = ref<any[]>([]);
const loadingHistory = ref(false);

// 工具方法
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString();
};

const formatJson = (json: string | undefined) => {
  if (!json) return '';
  try {
    return JSON.stringify(JSON.parse(json), null, 2);
  } catch {
    return json;
  }
};

// 历史记录相关方法
const handleClearHistory = () => {
  historyData.value = [];
  window.$message?.success('历史记录已清空');
};

const handleRefreshHistory = async () => {
  loadingHistory.value = true;
  try {
    const response = await getMqMessageRecords(100); // 获取最近100条记录
    if (response && response.data && Array.isArray(response.data)) {
      // 适应后端API的响应格式，使用response.data
      historyData.value = response.data.map((record, index) => ({
        ...record,
        id: record.messageId || `record-${index}` // 确保每条记录有唯一ID
      }));
      window.$message?.success('历史记录已刷新');
    } else {
      window.$message?.warning('未获取到历史记录数据');
    }
  } catch (error: any) {
    console.error('获取历史记录失败:', error);
    window.$message?.error(`获取历史记录失败: ${error.message || '未知错误'}`);
  } finally {
    loadingHistory.value = false;
  }
};

const handleViewHistoryDetail = (record: any) => {
  selectedHistoryRecord.value = record;
  showHistoryDetail.value = true;
};

// 工具函数
const getTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    ASYNC_REQUEST: 'blue',
    SYNC: 'green',
    ASYNC_REPLY: 'orange'
  };
  return colors[type] || 'default';
};

const getTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    ASYNC_REQUEST: '异步请求',
    SYNC: '同步消息',
    ASYNC_REPLY: '异步回复'
  };
  return labels[type] || type;
};

// 历史记录表格列配置
const historyColumns: TableColumnsType = [
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    width: 120
  },
  {
    title: '租户ID',
    dataIndex: 'tenantId',
    key: 'tenantId',
    width: 120,
    ellipsis: true
  },
  {
    title: '消息ID',
    dataIndex: 'messageId',
    key: 'messageId',
    width: 120,
    ellipsis: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '节点',
    dataIndex: 'nodeInfo',
    key: 'nodeInfo',
    width: 150,
    ellipsis: true
  },
  {
    title: 'URL',
    dataIndex: 'url',
    key: 'url',
    width: 200,
    ellipsis: true
  },
  {
    title: '时间',
    dataIndex: 'timestamp',
    key: 'timestamp',
    width: 180,
    customRender: ({ text }) => formatDateTime(text)
  },
  {
    title: '操作',
    key: 'action',
    width: 100,
    fixed: 'right'
  }
];

// 生命周期
onMounted(() => {
  console.log('MQ消息测试历史页面初始化');
  handleRefreshHistory();
});
</script>

<template>
  <div>
    <!-- 测试历史记录面板 -->
    <ACard title="MQ消息测试历史记录" size="small">
      <template #extra>
        <ASpace>
          <AButton type="text" danger @click="handleClearHistory">
            <template #icon>
              <DeleteOutlined />
            </template>
            清空历史
          </AButton>
          <AButton type="text" @click="handleRefreshHistory">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </AButton>
        </ASpace>
      </template>
      <ATable
        :columns="historyColumns"
        :data-source="historyData"
        :pagination="{ pageSize: 20, showSizeChanger: true }"
        size="small"
        :row-key="(record: any) => record.id"
        :loading="loadingHistory"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.key === 'type'">
            <ATag :color="getTypeColor(text)">
              {{ getTypeLabel(text) }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'status'">
            <ATag :color="text === 'SUCCESS' ? 'success' : 'error'">
              {{ text }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <AButton type="link" @click="handleViewHistoryDetail(record)">查看详情</AButton>
          </template>
        </template>
      </ATable>
    </ACard>

    <!-- 历史记录详情抽屉 -->
    <ADrawer v-model:open="showHistoryDetail" title="测试记录详情" width="600" placement="right">
      <ADescriptions :column="1" bordered>
        <ADescriptionsItem label="消息ID">
          {{ selectedHistoryRecord?.messageId }}
        </ADescriptionsItem>
        <ADescriptionsItem label="消息类型">
          <ATag :color="getTypeColor(selectedHistoryRecord?.type)">
            {{ getTypeLabel(selectedHistoryRecord?.type) }}
          </ATag>
        </ADescriptionsItem>
        <ADescriptionsItem label="租户ID">
          {{ selectedHistoryRecord?.tenantId }}
        </ADescriptionsItem>
        <ADescriptionsItem label="节点信息">
          {{ selectedHistoryRecord?.nodeInfo || '未知' }}
        </ADescriptionsItem>
        <ADescriptionsItem label="请求URL">
          {{ selectedHistoryRecord?.url || '无' }}
        </ADescriptionsItem>
        <ADescriptionsItem label="测试时间">
          {{ formatDateTime(selectedHistoryRecord?.timestamp) }}
        </ADescriptionsItem>
        <ADescriptionsItem label="执行状态">
          <ATag :color="selectedHistoryRecord?.status === 'SUCCESS' ? 'success' : 'error'">
            {{ selectedHistoryRecord?.status }}
          </ATag>
        </ADescriptionsItem>
        <ADescriptionsItem v-if="selectedHistoryRecord?.error" label="错误信息">
          <ATypographyText type="danger">{{ selectedHistoryRecord.error }}</ATypographyText>
        </ADescriptionsItem>
        <ADescriptionsItem label="消息内容">
          <ATypographyParagraph>
            <pre>{{ formatJson(selectedHistoryRecord?.content) }}</pre>
          </ATypographyParagraph>
        </ADescriptionsItem>
        <ADescriptionsItem v-if="selectedHistoryRecord?.responseContent" label="响应内容">
          <ATypographyParagraph>
            <pre>{{ formatJson(selectedHistoryRecord?.responseContent) }}</pre>
          </ATypographyParagraph>
        </ADescriptionsItem>
        <ADescriptionsItem v-if="selectedHistoryRecord?.properties" label="消息属性">
          <ATypographyParagraph>
            <pre>{{ formatJson(selectedHistoryRecord?.properties) }}</pre>
          </ATypographyParagraph>
        </ADescriptionsItem>
      </ADescriptions>
    </ADrawer>
  </div>
</template>

<style scoped>
pre {
  /* background-color: #f5f5f5; */
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  overflow-x: auto;
}

/* 修复按钮图标和文字的对齐问题 */
:deep(.ant-btn-text) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-btn-text .anticon) {
  display: inline-flex;
  align-items: center;
  margin-right: 4px;
}
</style>
